/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.Tools;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.SecretBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.stub.Port;
import com.koron.common.web.Util;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.mapper.IndicationItemsMapper;
import com.koron.hazardsource.util.Immutable;
import com.koron.hazardsource.util.RiskLevelDesc;
import com.koron.hiddendanger.domain.FreeSnap;
import com.koron.hiddendanger.domain.HiddenDangerDiscovery;
import com.koron.hiddendanger.domain.HiddenDangerRectification;
import com.koron.hiddendanger.mapper.FreeSnapMapper;
import com.koron.hiddendanger.mapper.HiddenDangerMapper;
import com.koron.hiddendanger.service.api.FreeSnapService;
import com.koron.hiddendanger.service.api.HiddenDangerDiscoveryService;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.risk.bean.SourceQueryBean;
import com.koron.risk.domain.LocalHazardSource;
import com.koron.risk.service.api.GridNodeService;
import com.koron.risk.service.api.LocalHazardSourceService;
import com.koron.risk.util.GridHelpUtils;
import com.koron.system.domain.DictData;
import com.koron.system.domain.Message;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.mapper.MessageMapper;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FreeSnapServiceImpl implements FreeSnapService, AfterApprovalService, InitializingBean {
    @Value("${app.orgCode}")
    private String orgCode;
    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;

    private final static  Logger logger = LoggerFactory.getLogger(FreeSnapServiceImpl.class);
    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private HiddenDangerDiscoveryService dangerDiscoveryService;

    @Autowired
    private FlowManagement flowManagement;

    @Autowired
    private GridNodeService nodeService;

    @Autowired
    private LocalHazardSourceService sourceService;

    @Autowired
    private Util util;

    @Value("${free_snap_confirmation}")
    private String freeSnapConfirm;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Value("${danger_work_flow}")
    private String hiddenDangerWorkFlow;

    @Autowired
    private GridHelpUtils helpUtils;

    @Override
    public MessageBean<Integer> saveOrCommit(StaffBean user, FreeSnap snap, Integer operationType, MultipartFile[] files,
                                             String delFileAddress, String keepFileAddress) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        String[] keepAddressArray = StringUtils.isEmpty(keepFileAddress) ? null : keepFileAddress.split("[,，]");
        List<String> keepAddressList = new ArrayList<>();
        if (keepAddressArray != null && keepAddressArray.length > 0) {
            keepAddressList = Arrays.asList(keepAddressArray).stream().collect(Collectors.toList());
        }
        try {
            if (null == operationType) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_OPERATIONTYPE.getDescription());
                return msg;
            }
            if (1 != operationType && 0 != operationType) {
                msg.setCode(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(snap.getDescription())) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_DESCRIPTION.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_DESCRIPTION.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(snap.getCorpCode())) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_CORPCODE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_CORPCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(snap.getGridCode())) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_GRIDCODE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_GRIDCODE.getDescription());
                return msg;
            }
            if ((files == null ? 0 : files.length) + (keepAddressArray == null ? 0 : keepAddressArray.length) > 3) {
                msg.setCode(BusinessCode.FREESNAP_FILE_GREATER.getCode());
                msg.setDescription(BusinessCode.FREESNAP_FILE_GREATER.getDescription());
                return msg;
            }
            // 上传图片
            if (null != files) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    String filpath = url + "#" + file.getOriginalFilename();
                    keepAddressList.add(filpath);
                }
            }
            List<DeptBean> deptBeanList = getPort().dept(snap.getSubmiterCode()).getData();
            if (null != deptBeanList && deptBeanList.size() > 0)
                snap.setSubmitDepartmentName(deptBeanList.get(0).getName());
            Audit audit = null;
            if (1 == operationType) {
                if (StringUtils.isEmpty(snap.getSubmiterCode())) {
                    msg.setCode(BusinessCode.FREESNAP_EMPTY_SUBMITCODE.getCode());
                    msg.setDescription(BusinessCode.FREESNAP_EMPTY_SUBMITCODE.getDescription());
                    return msg;
                }
                snap.setState(1);
                snap.setSubmitTime(snap.getUpdateTime());
                // 构造audit
                audit = new Audit();
                audit.setId(DefaultIdGenerator.getInstance().generateLongId());
                audit.setUpdateUser(snap.getUpdateUser());
                audit.setUpdateTime(snap.getUpdateTime());
                audit.setAddUser(snap.getUpdateUser());
                audit.setAddTime(snap.getUpdateTime());
                audit.setFlowType(2);
                audit.setOperation(1);
                audit.setTarget(FreeSnapServiceImpl.class.getName());
                audit.setFlowName(Immutable.CONMFIRM_FREESNAP);
                //audit.setTitle( snap.getUpdateUser() + "提交了一份随手拍待确认");
                audit.setTitle("随手拍待确认");
                audit.setCorpCode(snap.getCorpCode());
                audit.setInitiatorCode(snap.getSubmiterCode());
                audit.setDescription(snap.getDescription());
                audit.setState(1);
                audit.setTemplateKey(freeSnapConfirm);
                audit.setInitiatorAccount(user.getUserid());
                audit.setSetCode(riskDangerSetCode);
            } else {
                snap.setState(0);
                snap.setSubmitTime(null);
            }
            FreeSnapMapper snapMapper = factory.getMapper(FreeSnapMapper.class);
            if (StringUtils.isEmpty(snap.getId())) {
                // 新增
                snap.setAddTime(snap.getUpdateTime());
                snap.setAddUser(snap.getUpdateUser());
                snap.setId(DefaultIdGenerator.getInstance().generateLongId());
                snap.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                snap.setCode(Tools.getCode32());
                if (StringUtils.isEmpty(snap.getDeviceCode())) {
                    snap.setDeviceCode("LSFS-" + snap.getId().substring(snap.getId().length() - 8));
                }
                snapMapper.insert(snap);
            } else {
                // 修改
                if (StringUtils.isEmpty(snap.getId())) {
                    msg.setCode(BusinessCode.FREESNAP_EMPTY_ID.getCode());
                    msg.setDescription(BusinessCode.FREESNAP_EMPTY_ID.getDescription());
                    return msg;
                }
                FreeSnap en = queryOne(snap.getId()).getData();
                if (null == en) {
                    msg.setCode(BusinessCode.FREESNAP_NOT_EXISIT.getCode());
                    msg.setDescription(BusinessCode.FREESNAP_NOT_EXISIT.getDescription());
                    return msg;
                }
                if (en.getState() != 0) {
                    msg.setCode(BusinessCode.FREESNAP_IS_SUBMITTED.getCode());
                    msg.setDescription(BusinessCode.FREESNAP_IS_SUBMITTED.getDescription());
                    return msg;
                }
                snap.setAttachment((keepAddressList == null || keepAddressList.size() <= 0) ? null : new Gson().toJson(keepAddressList));
                if (StringUtils.isEmpty(snap.getDeviceCode())) {
                    snap.setDeviceCode("LSFS-" + snap.getId().substring(snap.getId().length() - 8));
                }
                snapMapper.update(snap);
                if (StringUtils.isNotEmpty(delFileAddress)) {
                    String[] delArray = delFileAddress.split("[,，]");
                    for (String delAdr : delArray) {
                        clientWrapper.deleteFile(delAdr.split("#")[0]);
                    }
                }
            }
            if (null != audit) {
                audit.setBusinessIds(snap.getId());
                Map<String, Object> businessMap = new HashMap<>();
                //根据网格id获取当前网格负责人code,并将
                String gridManager = helpUtils.getGridManager(snap.getGridCode(), audit);
                if (StringUtils.isEmpty(gridManager)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.NOT_FOUNT_GRIDMANAGER.getCode());
                    msg.setDescription(BusinessCode.NOT_FOUNT_GRIDMANAGER.getDescription());
                    return msg;
                }
                businessMap.put("gridManager", gridManager);
                if (!flowManagement.initFlow(user, audit, businessMap)) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription("提交随手拍失败");
                    return msg;
                } else {
                    factory.close();
                    msg.setCode(BusinessCode.SUCCESS.getCode());
                    msg.setDescription("提交随手拍成功");
                    return msg;
                }
            }
            factory.close();
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("保存成功");
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            for (String add : keepAddressList) {
                for (String keepAdd : keepAddressArray) {
                    if (!add.equals(keepAdd)) {
                        clientWrapper.deleteFile(add.split("#")[0]);
                    }
                }
            }
            if (null != factory) {
                factory.close(false);
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<DataBean<FreeSnap>> queryByCondition(StaffBean user, String description, String corpCode, String gridCode,
                                                            Integer state, Date submitTimeStart, Date submitTimeEnd, String departCode, String submitCode,
                                                            String submitDepartmentName, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<FreeSnap>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<String> submitCodeList = new ArrayList<>();
            if (StringUtils.isNotEmpty(departCode)) {
                Port port = getPort();
                List<StaffBean> staffBeanList = port.depstaff(orgCode, departCode, 0).getData();
                submitCodeList = staffBeanList.stream().map((item) -> item.getCode()).collect(Collectors.toList());
            }
            if (StringUtils.isNotEmpty(submitCode)) {
                submitCodeList = new ArrayList<>();
                submitCodeList.add(submitCode);
            }
            List<FreeSnap> list = new ArrayList<>();
            List<FreeSnap> freeSnaps = factory.getMapper(FreeSnapMapper.class).queryByCondition(description, corpCode,
                    gridCode, state, submitTimeStart, submitTimeEnd, submitCodeList, submitDepartmentName, null, rows,keyword);
            int count = 0;
            if (null != freeSnaps && freeSnaps.size() > 0) {
                for (FreeSnap freeSnap : freeSnaps) {
                    if (freeSnap.getState() == 0) {
                        if (freeSnap.getSubmiterCode().equals(user.getCode())) {
                            list.add(freeSnap);
                        } else {
                            count++;
                        }
                    } else {
                        list.add(freeSnap);
                    }
                }
            }
            Integer totalNumber = factory.getMapper(FreeSnapMapper.class).countByCondition(description, corpCode,
                    gridCode, state, submitTimeStart, submitTimeEnd, submitCodeList, submitDepartmentName,keyword);
            totalNumber = totalNumber - count;
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            Integer end = start + rows;
            if (end > list.size()) {
                end = list.size();
                if (start > end) {
                    start = end;
                }
            }
            //list.subList(start,end).forEach(item->getNames(item));
            DataBean<FreeSnap> dataBean = new DataBean<>();
            dataBean.setList(list.subList(start, end));
            dataBean.setTotalNumber(totalNumber);
            dataBean.setTotalPage(totalPage);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询随手拍列表成功");
            msg.setData(dataBean);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> deleteBatch(List<String> idList) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null == idList || idList.size() <= 0) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_CHANGE_DATA.getDescription());
                return msg;
            }
            List<String> delIdList = new ArrayList<>();
            List<String> attList = new ArrayList<>();
            for (String id : idList) {
                FreeSnap snap = queryOne(id).getData();
                if (null != snap && snap.getState() == 0) {
                    delIdList.add(id);
                    if (StringUtils.isNotEmpty(snap.getAttachment())) {
                        for (String att : snap.getAttachment().split("[,，]")) {
                            attList.add(att);
                        }
                    }
                }
            }
            if (delIdList == null || delIdList.size() <= 0) {
                msg.setCode(BusinessCode.FREESNAP_IS_SUBMITTED.getCode());
                msg.setDescription(BusinessCode.FREESNAP_IS_SUBMITTED.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(FreeSnapMapper.class).deleteBatch(delIdList);
            if (value > 0) {
                if (attList != null && attList.size() > 0) {
                    for (String att : attList) {
                        clientWrapper.deleteFile(att.split("#")[0]);
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("删除成功");
                msg.setData(value);
                factory.close();
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
                msg.setData(value);
                factory.close(false);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> confirmFreeSnap(FreeSnap snap, StaffBean user, Integer operationType, String feedback, LocalHazardSource localHazardSource, HiddenDangerDiscovery dangerDiscovery) {
        MessageBean<Integer> msg = new MessageBean<>();
        SessionFactory factory = new SessionFactory();
        try {
            FreeSnapMapper snapMapper = factory.getMapper(FreeSnapMapper.class);
            if (null == operationType) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_OPERATIONTYPE.getDescription());
                return msg;
            }
            if (operationType != 0 && operationType != 2) {
                msg.setCode(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getCode());
                msg.setDescription(BusinessCode.FREESNAP_ILEAGEL_OPERATIONTYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(snap.getId())) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_ID.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_ID.getDescription());
                return msg;
            }
            FreeSnap en = queryOne(snap.getId()).getData();
            if (null == en) {
                msg.setCode(BusinessCode.FREESNAP_NOT_EXISIT.getCode());
                msg.setDescription(BusinessCode.FREESNAP_NOT_EXISIT.getDescription());
                return msg;
            }
            snap.setState(operationType == 2 ? 3 : 2);
            snap.setConfirmerCode(user.getCode());
            snap.setConfirmTime(new Date());
            snap.setFeedback(feedback);
            if (operationType == 0) {
                // 确认为隐患
                // snap.setDangerId();
                List<DeptBean> deptBeanList = getPort().dept(user.getCode()).getData();
                if (StringUtils.isEmpty(dangerDiscovery.getDangerManager())) {
                    msg.setCode(BusinessCode.DANGERRECTIFICATION_EMPTY_RECTIFIER.getCode());
                    msg.setDescription(BusinessCode.DANGERRECTIFICATION_EMPTY_RECTIFIER.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDescription())) {
                    msg.setCode(BusinessCode.DANGER_EMPTY_DESCRIPTION.getCode());
                    msg.setDescription(BusinessCode.DANGER_EMPTY_DESCRIPTION.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerType())) {
                    msg.setCode(BusinessCode.DANGER_EMPTY_DANGERTYPE.getCode());
                    msg.setDescription(BusinessCode.DANGER_EMPTY_DANGERTYPE.getDescription());
                    return msg;
                }
                if (StringUtils.isEmpty(dangerDiscovery.getDangerLevel())) {
                    msg.setCode(BusinessCode.DANGER_EMPTY_DANGERLEVEL.getCode());
                    msg.setDescription(BusinessCode.DANGER_EMPTY_DANGERLEVEL.getDescription());
                    return msg;
                }
                if (StringUtils.isNotEmpty(dangerDiscovery.getInnerStaff())) {
                    String[] array = dangerDiscovery.getInnerStaff().split("[,，]");
                    List<String> codeList = Arrays.asList(array).stream().map(String::trim).collect(Collectors.toList());
                    dangerDiscovery.setInnerStaff(new Gson().toJson(codeList));
                }
                if (dangerDiscovery.getDangerManager().split("_").length == 1) {
                    List<StaffBean> list = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                    if (null != list && list.size() > 0) {
                        dangerDiscovery.setDangerManager(StringUtils.join(dangerDiscovery.getDangerManager(), "_", list.get(0).getUserid()));
                    }
                }
                dangerDiscovery.setId(DefaultIdGenerator.getInstance().generateLongId());
                dangerDiscovery.setCode(dangerDiscoveryService.generateCode(factory, dangerDiscovery));
                dangerDiscovery.setAddUser(user.getName());
                dangerDiscovery.setAddTime(snap.getConfirmTime());
                dangerDiscovery.setUpdateUser(user.getName());
                dangerDiscovery.setUpdateTime(snap.getConfirmTime());
                dangerDiscovery.setAttachment(snap.getAttachment());
                dangerDiscovery.setSubmitterCode(user.getCode() + "_" + user.getUserid());
                dangerDiscovery.setSubmitterDepartment(deptBeanList.get(0).getCode());
                // 获取随手拍确认人所属公司
                MessageBean<?> corpMsg = util.corp(user.getCode());
                if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                    DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                    dangerDiscovery.setCheckUnit(corp.getDepartmentCode());
                    dangerDiscovery.setCheckUnitName(corp.getName());
                }
                // 根据随手拍网格区域，找到其对应的公司
                DepartmentTreeBean corpBean = nodeService.getCorpInfo(factory, snap.getGridCode());
                if (null != corpBean) {
                    dangerDiscovery.setCorpCode(corpBean.getDepartmentCode());
                } else {
                    //查询网格所属公司失败,获取随手拍确认人所属公司
                    if (corpMsg.getCode() == 0 && null != corpMsg.getData()) {
                        DepartmentTreeBean corp = (DepartmentTreeBean) corpMsg.getData();
                        dangerDiscovery.setCorpCode(corp.getDepartmentCode());
                    }
                }
                dangerDiscovery.setGridCode(snap.getGridCode());
                dangerDiscovery.setGridName(snap.getGridName());
                dangerDiscovery.setDerivation(2);
                String submiterCode = snap.getSubmiterCode();
                MessageBean<List> staffMsg = getPort().staff(submiterCode);
                MessageBean<List> deptMsg = getPort().dept(submiterCode);
                if (null != staffMsg.getData() && staffMsg.getData().size() > 0) {
                    StaffBean staffBean = (StaffBean) staffMsg.getData().get(0);
                    dangerDiscovery.setDiscovererCode(new Gson().toJson(Arrays.asList(staffBean.getCode() + "_" + staffBean.getUserid())));
                    if (null != deptMsg.getData() && deptMsg.getData().size() > 0) {
                        DeptBean dept = (DeptBean) deptMsg.getData().get(0);
                        dangerDiscovery.setDiscovererDepartment(new Gson().toJson(Arrays.asList(staffBean.getName() + "_" + dept.getName())));
                    }
                }
                dangerDiscovery.setDiscoveryTime(snap.getSubmitTime());
                if (StringUtils.isNotEmpty(snap.getDeviceCode())) {
                    dangerDiscovery.setDeviceCode(snap.getDeviceCode());
                    //根据设备编码查询风险等级
                    SourceQueryBean bean = new SourceQueryBean();
                    bean.setCode(snap.getDeviceCode());
                    DataBean<LocalHazardSource> data = (DataBean<LocalHazardSource>) sourceService.list(bean).getData();
                    List<LocalHazardSource> localHazardSourceList = data.getList();
                    if (null != localHazardSourceList && localHazardSourceList.size() > 0) {
                        dangerDiscovery.setRiskLevelName(localHazardSourceList.get(0).getRiskLevelName());
                    } else {
                        //默认低风险
                        dangerDiscovery.setRiskLevelName("低风险");
                    }
                } else {
                    //默认低风险
                    dangerDiscovery.setRiskLevelName("低风险");
                }
                if (StringUtils.isNotEmpty(snap.getDeviceName())) {
                    dangerDiscovery.setDeviceName(snap.getDeviceName());
                }
                dangerDiscovery.setFreeSnapId(snap.getId());
                dangerDiscovery.setCheckRecordId(snap.getId());
                snap.setHiddenDangerId(dangerDiscovery.getId());
                dangerDiscovery.setState(0);
                if(null ==dangerDiscovery.getRectificationPeriod()){
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH,7);
                    dangerDiscovery.setRectificationPeriod(calendar.getTime());
                }
                //更新指标项引用计数
                List<IndicationItems> itemsList = new ArrayList<>();
                IndicationItems items1 = factory.getMapper(IndicationItemsMapper.class).queryOne(dangerDiscovery.getDangerType());
                if (null != items1) {
                    items1.setReferenceCount(items1.getReferenceCount() + 1);
                    itemsList.add(items1);
                }
                IndicationItems items2 = factory.getMapper(IndicationItemsMapper.class).queryOne(dangerDiscovery.getDangerLevel());
                if (null != items2) {
                    items2.setReferenceCount(items2.getReferenceCount() + 1);
                    itemsList.add(items2);
                }
                //更新数据字典引用计数
                List<DictData> dataList = new ArrayList<>();
                DictData data1 = factory.getMapper(DictDataMapper.class).queryOne(dangerDiscovery.getElementFristType());
                if (null != data1) {
                    data1.setReferenceCount(data1.getReferenceCount() + 1);
                    dataList.add(data1);
                }
                DictData data2 = factory.getMapper(DictDataMapper.class).queryOne(dangerDiscovery.getElementSecondType());
                if (null != data2) {
                    data2.setReferenceCount(data2.getReferenceCount() + 1);
                    dataList.add(data2);
                }
                factory.getMapper(HiddenDangerMapper.class).insertDanger(dangerDiscovery);
                //更新2个引用计数
                if (null != itemsList && itemsList.size() > 0) {
                    factory.getMapper(IndicationItemsMapper.class).batchUpdate(itemsList);
                }
                if (null != dataList && dataList.size() > 0) {
                    factory.getMapper(DictDataMapper.class).batchUpdate(dataList);
                }
            }
            snapMapper.update(snap);
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        } finally {
            if (null != factory) {
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<FreeSnap> queryOne(String id) {
        MessageBean<FreeSnap> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.FREESNAP_EMPTY_ID.getCode());
                msg.setDescription(BusinessCode.FREESNAP_EMPTY_ID.getDescription());
                return msg;
            }
            FreeSnap snap = factory.getMapper(FreeSnapMapper.class).queryOne(id);
            getNames(snap);
            msg.setData(snap);
            msg.setDescription("获取随手拍详情");
            msg.setCode(BusinessCode.SUCCESS.getCode());
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<FreeSnap> export(StaffBean user, String description, String corpCode, String gridCode, Integer state, Date submitTimeStart, Date submitTimeEnd, String departCode, String submitCode) {
        try (SessionFactory factory = new SessionFactory()) {
            List<String> submitCodeList = new ArrayList<>();
            if (StringUtils.isNotEmpty(departCode)) {
                Port port = getPort();
                List<StaffBean> staffBeanList = port.depstaff(orgCode, departCode, 0).getData();
                submitCodeList = staffBeanList.stream().map((item) -> item.getCode()).collect(Collectors.toList());
            }
            if (StringUtils.isNotEmpty(submitCode)) {
                submitCodeList = new ArrayList<>();
                submitCodeList.add(submitCode);
            }
            List<FreeSnap> list = new ArrayList<>();
            List<FreeSnap> freeSnaps = factory.getMapper(FreeSnapMapper.class).queryByCondition(description, corpCode,
                    gridCode, state, submitTimeStart, submitTimeEnd, submitCodeList, null, null, null,null);
            if (null != freeSnaps && freeSnaps.size() > 0) {
                for (FreeSnap freeSnap : freeSnaps) {
                    if (freeSnap.getState() == 0) {
                        if (freeSnap.getSubmiterCode().equals(user.getCode())) {
                            list.add(freeSnap);
                        }
                    } else {
                        list.add(freeSnap);
                    }
                }
            }
            list.forEach(this::getNames);
            factory.close();
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    private void getNames(FreeSnap bean) {
        if (null != bean) {
            Port port = getPort();
            SessionFactory factory = new SessionFactory();
            if (StringUtils.isNotEmpty(bean.getCorpCode())) {
                List<DepartmentTreeBean> departmentTreeBeanList = port.depttree(orgCode, bean.getCorpCode(), 0).getData();
                bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                        ? null : departmentTreeBeanList.get(0).getName());
            }
            if (StringUtils.isNotEmpty(bean.getGridCode()) && StringUtils.isEmpty(bean.getGridName())) {
                List<DepartmentTreeBean> treeBeanList = port.depttree(orgCode, bean.getGridCode(), 1).getData();
                if (null != treeBeanList && treeBeanList.size() > 0) {
                    bean.setGridName(treeBeanList.get(0).getName());
                }
            }
            factory.close();
        }
    }

    public Port getPort() {
        SecretBean secretBean = new SecretBean();
        secretBean.setAppid(appid);
        secretBean.setSecret(secret);
        return new Port(secretBean);
    }

    @Override
    public void editApproval(Audit audit) {
        try (SessionFactory factory = new SessionFactory()) {
            // 获取随手拍数据
            FreeSnap freeSnap = factory.getMapper(FreeSnapMapper.class).queryOne(audit.getBusinessIds());
            // 获取隐患数据
            List<HiddenDangerDiscovery> dangerDiscoveryList = factory.getMapper(FreeSnapMapper.class).queryDangerByFreeSnap(audit.getBusinessIds());
            // 随手拍审批完成后，自动启动隐患整改流程
            if (null != dangerDiscoveryList && dangerDiscoveryList.size() > 0) {
                // 获取随手拍确认人
                String confirmerCode = freeSnap.getConfirmerCode();
                List<StaffBean> submitStaffBeanList = (List<StaffBean>) util.staff(confirmerCode.split("_")[0], null).getData();
                StaffBean user = submitStaffBeanList.get(0);
                // 获取隐患负责人
                Set<String> codeLists = dangerDiscoveryList.stream().map(bean -> bean.getDangerManager().split("_")[0]).collect(Collectors.toSet());
                List<String> noticeCodeList = new ArrayList<>();
                for (String code : codeLists) {
                    try (SessionFactory sessionFactory = new SessionFactory()) {
                        // 同一个隐患负责人，提交成一条隐患流程
                        List<HiddenDangerDiscovery> discoveryList = dangerDiscoveryList.stream().filter(bean -> code.equals(bean.getDangerManager().split("_")[0])).collect(Collectors.toList());
                        //整理隐患整改记录
                        HiddenDangerMapper mapper = sessionFactory.getMapper(HiddenDangerMapper.class);
                        List<HiddenDangerRectification> rectificationList = new ArrayList<>();
                        List<HiddenDangerRectification> deleteList = new ArrayList<>();
                        List<String> approvalList = new ArrayList<>();
                        for (HiddenDangerDiscovery dangerDiscovery : discoveryList) {
                            //查询提交的隐患是不是已经有了整改记录；
                            List<HiddenDangerRectification> rectificationList1 = sessionFactory.getMapper(HiddenDangerMapper.class).queryRectificationByDangerRecordId(dangerDiscovery.getId());
                            //删除之前有的整改记录信息
                            if (rectificationList1 != null && rectificationList1.size() > 0) {
                                deleteList.addAll(rectificationList1);
                            }
                            //保存隐患整改信息，主要是配置隐患整改信息的验证人
                            HiddenDangerRectification rectification = new HiddenDangerRectification();
                            //保存整改信息
                            rectification.setHiddenDangerId(dangerDiscovery.getId());
                            rectification.setId(DefaultIdGenerator.getInstance().generateLongId());
                            rectification.setAddTime(dangerDiscovery.getUpdateTime());
                            rectification.setAddUser(user.getName());
                            rectification.setUpdateTime(dangerDiscovery.getUpdateTime());
                            rectification.setUpdateUser(user.getName());
                            rectification.setRectifier(dangerDiscovery.getDangerManager());
                            rectification.setRectifierName(dangerDiscovery.getDangerManagerName());
                            rectification.setDeadline(dangerDiscovery.getRectificationPeriod());
                            rectification.setSolution(dangerDiscovery.getDescription());
                            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(dangerDiscovery.getDangerManager().split("_")[0], null).getData();
                            List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(dangerDiscovery.getDangerManager().split("_")[0]).getData();
                            if (!approvalList.contains(staffBeanList.get(0).getUserid())) {
                                approvalList.add(staffBeanList.get(0).getUserid());
                            }
                            rectification.setReviewer(dangerDiscovery.getDangerManager().split("_")[0]);
                            rectification.setReviewerName(staffBeanList.get(0).getName() + "_" + deptBeanList.get(0).getName());
                            rectification.setDelayState(0);
                            IndicationItems items = sessionFactory.getMapper(IndicationItemsMapper.class).matchIndicationItems("隐患整改状态", "未整改");
                            rectification.setRectificationState(items == null ? null : items.getId());
                            rectificationList.add(rectification);
                        }
                        //更新选中的隐患为确认状态；启动隐患流程
                        List<String> ids = discoveryList.stream().map(bean -> bean.getId()).collect(Collectors.toList());
                        mapper.updateDangerState(2, ids);
                        try{
                            for (HiddenDangerDiscovery discovery : discoveryList) {
                                List<Message> messages = new ArrayList<>();
                                if(discovery.getCopyPerson() != null) {
                                    String[] copyPersons = discovery.getCopyPerson().split(",");
                                    for(String copyPerson : copyPersons) {
                                        Message message = new Message();
                                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                                        message.setTitle("有一项您关注的隐患整改");
                                        message.setIsRead(0);
                                        message.setIsRemove(0);
                                        message.setAddTime(new Date());
                                        message.setAddUser(discovery.getAddUser());
                                        message.setContent("隐患描述：" + discovery.getDescription());
                                        message.setReceiverCode(copyPerson.split("_")[0]);
                                        messages.add(message);
                                    }
                                }
                                if(messages != null && messages.size()> 0) {
                                    factory.getMapper(MessageMapper.class).batchInsert(messages);
                                }
                            }
                        }catch (Exception e){
                            logger.error(e.getMessage(),e);
                        }
                        mapper.batchInsertRectification(rectificationList);
                        if (deleteList != null && deleteList.size() > 0) {
                            List<String> deleteIdList = deleteList.stream().map(HiddenDangerRectification::getId).collect(Collectors.toList());
                            mapper.bateDeleteRectification(deleteIdList);
                        }
                        Date date = new Date();
                        Audit auditBean = new Audit();
                        auditBean.setId(DefaultIdGenerator.getInstance().generateLongId());
                        auditBean.setUpdateUser(user.getName());
                        auditBean.setUpdateTime(date);
                        auditBean.setAddTime(date);
                        auditBean.setAddUser(user.getName());
                        auditBean.setFlowType(2);
                        auditBean.setOperation(1);
                        auditBean.setTarget(HiddenDangerDiscoveryServiceImpl.class.getName());
                        auditBean.setFlowName(Immutable.HIDDENDANGER_WORKFLOW);
                        auditBean.setNowNodeCode("Process-task2");
                        auditBean.setTitle("隐患整改流程");
                        auditBean.setCorpCode(discoveryList.get(0).getCorpCode());
                        auditBean.setBusinessIds(new Gson().toJson(ids));
                        auditBean.setInitiatorCode(user.getCode());
                        auditBean.setTemplateKey(hiddenDangerWorkFlow);
                        auditBean.setInitiatorAccount(user.getUserid());
                        auditBean.setSetCode(riskDangerSetCode);
                        auditBean.setDescription("隐患整改流程");
                        auditBean.setState(1);
                        Map<String, Object> businessDataMap = new HashMap<>();
                        String userid = approvalList.stream().collect(Collectors.joining(","));
                        businessDataMap.put("rectifier", userid);
                        businessDataMap.put("reviewer", userid);
                        businessDataMap.put("verification", user.getUserid());
                        if (!flowManagement.initFlow(user, auditBean, businessDataMap)) {
                            // 如果自动提交隐患失败，将隐患修改为草稿，可在隐患台账处提交
                            factory.getMapper(HiddenDangerMapper.class).updateDangerState(0, ids);
                            sessionFactory.close(false);
                        } else {
                            // 提交成功，生成整改通知书
                            String noticeCode = HiddenDangerRectificationServiceImpl.generateHiddenDangerRectificationNotice(sessionFactory, user, discoveryList);
                            if (StringUtils.isNotEmpty(noticeCode)) {
                                noticeCodeList.add(noticeCode);
                            }
                            sessionFactory.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void discardApproval(Audit audit) {
    }

    @Override
    public void processDiscard(Audit audit) {
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(FreeSnapServiceImpl.class.getName(), this);
    }

    private static Map<RiskLevelDesc, List<Integer>> levelMap = new HashMap<>();

    static {
        levelMap.put(RiskLevelDesc.Minor, Arrays.asList(1, 2, 3, 4));
        levelMap.put(RiskLevelDesc.Ordinary, Arrays.asList(5, 6, 8, 9));
        levelMap.put(RiskLevelDesc.Serious, Arrays.asList(10, 12, 15, 16));
        levelMap.put(RiskLevelDesc.Important, Arrays.asList(20, 25));
    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
